package com.learn.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;

/**
 * @author DJJ_F
 * @version 1.0
 * @date 2025/02/18
 * @description 获取SqlSession的工具类
 */
public class SqlSessionUtil {
    // 私有化构造方法防止，外部创建类
    private SqlSessionUtil() {}
    // 因为一个sqlSessionFactory对应一个数据库，所以只用创建一个对象
    private static SqlSessionFactory sqlSessionFactory;
    static {
        try {
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    public static SqlSession openSession() {
        return sqlSessionFactory.openSession();
    }
}
